package cc.sunwl.study.springboot2.controller;

import cc.sunwl.study.springboot2.entity.Article;
import cc.sunwl.study.springboot2.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * Flux多值:在流场景里使用（作为@RequestBody使用的输入流以及包含了Flux返回类型的Server Sent Events）。
 * Mono单值:作为@RequestBody，请求实体T会被异步反序列化，之后的处理可以跟Mono关联起来。作为返回类型，每次Mono发出了一个值，T就会被异步序列化并发回客户端。你可以把请求Mono作为参数，并把参数化了的关联处理作为结果Mono返回。
 */
@RestController
@RequestMapping("article")
public class ArticleController {

    private final ArticleService articleService;

    @Autowired
    public ArticleController(ArticleService articleService) {
        this.articleService = articleService;
    }

    @PostMapping("add")
    public Mono<Article> add(@RequestBody Article entity) {
        return articleService.add(entity);
    }

    /*@GetMapping("{id}")
    public Mono<ResponseEntity<Article>> get(@PathVariable String id) {
        return articleRepo.findById(id)
                .map(ResponseEntity::ok)
                .defaultIfEmpty(ResponseEntity.status(404).body(null));
    }*/
    @GetMapping("get/{id}")
    public Mono<Article> get(@PathVariable String id) {
        // Mono<ResponseEntity<Article>> responseEntityMono = articleService.get(id).map(ResponseEntity::ok).defaultIfEmpty(ResponseEntity.status(404).body(null));
        return articleService.get(id);
        // return responseEntityMono;
    }

    @PutMapping("put")
    public Mono<Article> put(@RequestBody Article entity) {
        return articleService.put(entity);
    }

    @DeleteMapping("del/{id}")
    public Mono<Void> del(@PathVariable String id) {
        return articleService.delete(id);
    }

    @GetMapping("get/list")
    public Flux<Article> list(int page, int size) {
        return articleService.list(page, size);
    }
}
